// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)

#include <muduo/base/CountDownLatch.h>

using namespace muduo;

CountDownLatch::CountDownLatch(int count)
	: mutex_(),
	condition_(mutex_),
	count_(count)
{
}

void CountDownLatch::wait()
{
	MutexLockGuard lock(mutex_); // 首先加锁
	while (count_ > 0)
	{
		condition_.wait(); // 只要count_>0就一直等待
	}
}

void CountDownLatch::countDown()
{
	MutexLockGuard lock(mutex_);
	--count_;
	if (count_ == 0)
	{
		condition_.notifyAll();
	}
}

int CountDownLatch::getCount() const
{
	MutexLockGuard lock(mutex_);
	return count_;
}

